package jmu.edu.yjc.controller;

import jmu.edu.yjc.Utils.BeanCopyUtil;
import jmu.edu.yjc.Utils.RedisCache;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.dto.ArticleDto;
import jmu.edu.yjc.domain.entity.Article;
import jmu.edu.yjc.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;

@RestController
@RequestMapping("/content/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;
    @Resource
    private RedisCache redisCache;
    @PostMapping
    public ResponseResult addArticle(@RequestBody ArticleDto articleDto){
        return articleService.addArticle(articleDto);
    }
    @GetMapping("/list")
    public ResponseResult list(Article article, Integer pageNum, Integer pageSize)
    {
        return articleService.selectArticlePage(article,pageNum,pageSize,null);
    }
    @GetMapping("/{id}")
    public ResponseResult editArticle(@PathVariable("id") Long id){
        Article article = articleService.getById(id);
        return ResponseResult.okResult(article);
    }
    @PutMapping
    public ResponseResult doEditArticle(@RequestBody ArticleDto articleDto){
        Article article = BeanCopyUtil.copyBeans(articleDto, Article.class);
        //更新博客信息
        articleService.updateById(article);
        return ResponseResult.okResult();
    }
    @DeleteMapping("/{id}")
    public ResponseResult delArticle(@PathVariable("id")String id){
        String[] ids = id.split(",");
        articleService.removeByIds(Arrays.asList(ids));
        //删除redis中的信息
        for (String i : ids) {
            redisCache.delCacheMapValue("article:viewCount",i);
        }
        return ResponseResult.okResult();
    }
    @GetMapping("/total")
    public ResponseResult getTotal() {
        return ResponseResult.okResult(articleService.count());
    }
}
